<template>
  <el-dialog
    :title="controlDeviceInfo.name + '-任务列表'"
    :append-to-body="true"
    :visible="visible"
    width="80%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="close"
  >
    <div>
      <el-row :gutter="10">
        <el-form ref="form" :model="searchForm" label-width="auto" size="small">
          <el-col :span="5" :offset="0">
            <el-form-item label="零件号">
              <el-input v-model="searchForm.partNumber" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="5" :offset="0">
            <el-form-item label="批次号">
              <el-input v-model="searchForm.batchNumber" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="5" :offset="0">
            <el-form-item label="工序号">
              <el-input
                v-model="searchForm.processNumber"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="5" :offset="0">
            <el-form-item label="工序名称">
              <el-input
                v-model="searchForm.name1"
                placeholder="请输入"
              ></el-input> </el-form-item
          ></el-col> -->
          <el-col :span="4" :offset="0">
            <el-button size="small" type="primary" @click="onSearchSubmit"
              >搜索</el-button
            >
            <el-button size="small" @click="handleReset">重置</el-button>
          </el-col>
        </el-form>
      </el-row>
      <el-table :data="tableData" size="small" border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-table
              :data="scope.row.childrenList.length"
              border
              size="mini"
              v-if="scope.row.childrenList"
            >
              <el-table-column type="index" label="序号" />
              <el-table-column
                prop="taskchildnumber"
                label="子任务号"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  {{ scope.row.taskchildnumber || "-" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="partNumber"
                show-overflow-tooltip
                label="零件号"
              >
                <template slot-scope="scope">
                  {{ scope.row.partNumber || "-" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="batchNumber"
                show-overflow-tooltip
                label="批次号"
              >
                <template slot-scope="scope">
                  {{ scope.row.batchNumber || "-" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="processNumber"
                show-overflow-tooltip
                label="工序号"
              >
                <template slot-scope="scope">
                  {{ scope.row.processNumber || "-" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="processName"
                show-overflow-tooltip
                label="工序名称"
                width="120"
              >
                <template slot-scope="scope">
                  {{ scope.row.processName || "-" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="partTotalCount"
                show-overflow-tooltip
                label="数量"
                ><template slot-scope="scope">
                  {{ scope.row.partTotalCount || "-" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="materialMark"
                show-overflow-tooltip
                label="材料牌号"
                ><template slot-scope="scope">
                  {{ scope.row.materialMark || "-" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="craftVersion"
                show-overflow-tooltip
                label="工艺版次"
                ><template slot-scope="scope">
                  {{ scope.row.craftVersion || "-" }}
                </template>
              </el-table-column>
            </el-table>
            <el-table
              style="margin-top: 10px"
              :data="renderStageTable(scope.row)"
              border
              size="mini"
            >
              <el-table-column
                prop="stageId"
                show-overflow-tooltip
                label="阶段号"
                ><template slot-scope="downscope">
                  {{ downscope.row.stageId || "-" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="setTemp"
                label="设定温度"
                show-overflow-tooltip
                ><template slot-scope="downscope">
                  {{ downscope.row.setTemp || "-" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="setTime"
                show-overflow-tooltip
                label="设定时间"
                ><template slot-scope="downscope">
                  {{ downscope.row.setTime || "-" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="volumeTemp"
                show-overflow-tooltip
                label="温度公差"
                ><template slot-scope="downscope">
                  {{ downscope.row.volumeTemp || "-" }}
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          type="index"
          width="80"
          label="序号"
          align="center"
        />
        <el-table-column
          show-overflow-tooltip
          prop="taskNumber"
          label="任务号"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.taskNumber || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="partName"
          label="状态"
          align="center"
        >
          <template slot-scope="scope">
            {{
              scope.row.taskStatus !== ""
                ? TASK_STATUS[Number(scope.row.taskStatus)]
                : "-"
            }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="lastOutTime"
          label="时间"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.createdDate | formatDate }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="partNumber"
          label="零件号"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.partName || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="batchNumber"
          label="批次号"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.batchNumber || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="processNumber"
          label="工序号"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.processNumber || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="processName"
          label="工序名称"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.processName || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="partTotalCount"
          label="数量"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.partTotalCount || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="materialMark"
          label="材料牌号"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.materialMark || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="craftVersion"
          label="工艺版次"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.craftVersion || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <i
              class="el-icon-edit"
              style="font-size: 18px; margin-right: 10px; color: #409eff"
              @click="editStage(scope.row)"
            />
            <i
              class="el-icon-bottom"
              style="font-size: 18px; color: #409eff"
              @click="handleIssued(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <span slot="footer">
      <el-button size="small" @click="close"> 取 消</el-button>
    </span>
    <StageComs
      :stage-btnloading="stageBtnloading"
      :formula-parameter="stageTable"
      :stage-visible.sync="stageVisible"
      :is-issued="isIssued"
      @submit="submit"
    />
  </el-dialog>
</template>

<script>
import {
  updateFormulaDownloadInfo,
  getTaskDownLoadInfos,
  formulaEdit
} from "@/api/deviceOperation";
import { useTable, TASK_STATUS } from "../../../js/utils";
import StageComs from "./Stage.vue";
import _ from "lodash";
import { mapGetters } from "vuex";
export default {
  components: { StageComs },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    deviceToken: {
      type: String,
      default: ""
    },
    deviceName: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      isIssued: false,
      TASK_STATUS,
      stageVisible: false,
      tableData: [],
      searchForm: {
        partNumber: "",
        batchNumber: "",
        processNumber: ""
      },
      rules: {},
      form: {},
      row: {},
      stageTable: [],
      stageBtnloading: false
    };
  },
  computed: {
    ...mapGetters(["controlDeviceInfo"]),
    renderStageTable() {
      return function(row) {
        const { formulaDownloadInfo } = row;
        if (!formulaDownloadInfo.stageId.length) {
          return [];
        }
        const arr = [];
        formulaDownloadInfo.stageId.forEach((item, index) => {
          arr.push({
            setTemp: formulaDownloadInfo["setTemp"][index], //  //设定温度
            setTime: formulaDownloadInfo["setTime"][index], // 设定改时间
            volumeTemp: formulaDownloadInfo["volumeTemp"][index], // 温度公差
            stageId: formulaDownloadInfo["stageId"][index] // 阶段
          });
        });

        console.log("tableData :>> ", arr);
        return arr;
      };
    }
  },
  watch: {
    //  //
    //  //阶段
    // deviceToken: {
    //   handler: function (newData, oldData) {
    //     console.info("任务下发是否存在token", newData);
    //     if (newData) {
    //       this.getTaskDownLoadInfos();
    //     }
    //   },
    //   immediate: true,
    // },
  },
  mounted() {
    // 获取任务下发弹框列表
  },
  methods: {
    // 拼接最终提交的阶段信息
    renderFormulaDownloadInfo() {
      const row = this.tableData.find(item => this.row.id == item.id);
      const { formulaDownloadInfo } = row;
      return {
        ...formulaDownloadInfo,
        setTemp: this.stageTable.map(item => item.setTemp),
        setTime: this.stageTable.map(item => item.setTime),
        volumeTemp: this.stageTable.map(item => item.volumeTemp),
        stageId: this.stageTable.map((item, index) => index + 1)
      };
    },
    // 阶段提交
    async submitStage() {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await formulaEdit([this.row.taskId]);
          this.stageBtnloading = false;
          const { data } = res;
          if (data) {
            this.$msg({
              type: "success",
              message: "下发成功"
            });
            resolve();
          } else {
            this.$msg("下发失败");
            reject();
          }
        } catch (error) {
          this.$msg("下发失败");
          this.stageBtnloading = false;
          reject();
        }
      });
    },
    // 编辑阶段
    submitInfo() {
      return new Promise((resolve, reject) => {
        updateFormulaDownloadInfo(
          this.renderFormulaDownloadInfo(this.stageTable)
        ).then(res => {
          resolve();
        });
      });
    },
    // 阶段/下发提交
    async submit() {
      if (!this.stageTable.length) {
        this.$msg("请添加阶段信息");
        return;
      }
      this.stageBtnloading = true;
      await this.submitInfo();
      // 下发
      if (this.isIssued) {
        await this.submitStage();
      } else {
        this.$msg({
          type: "success",
          message: "编辑成功"
        });
      }
      this.stageBtnloading = false;
      this.stageVisible = false;
      this.getTaskDownLoadInfos();
    },
    async editStage(row) {
      this.isIssued = false;
      const s = row.formulaDownloadInfo.stageId.length;
      this.stageTable = s ? this.renderStageTable(row) : [];
      this.row = _.cloneDeep(row);
      this.stageVisible = true;
      // const res = await formulaRecordDetails(row.token);
    },
    // 下发
    handleIssued(row) {
      const s = row.formulaDownloadInfo.stageId.length;
      this.stageTable = s ? this.renderStageTable(row) : [];
      this.row = _.cloneDeep(row);
      this.isIssued = true;
      this.stageVisible = true;
    },
    // 任务列表
    async getTaskDownLoadInfos() {
      const res = await getTaskDownLoadInfos({
        deviceToken: this.deviceToken,
        ...this.searchForm,
        taskStatus: 0
      });
      const { results } = res.data;
      // this.tableData = results;
      this.tableData = results;

      console.log("任务列表 :>> ", this.tableData);
    },
    handleReset() {
      Object.assign(this.$data.searchForm, this.$options.data().searchForm);
      this.getTaskDownLoadInfos();
    },
    // 搜索
    onSearchSubmit() {
      this.getTaskDownLoadInfos();
    },
    close() {
      this.$emit("update:visible", false);
    }
  }
};
</script>

<style></style>
